package cn.edu.xjtu.UDP;


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Hydrion-QLz
 * @date 2022-06-14 15:16
 * @description UDP服务器
 */
public class Server {
    public static void main(String[] args) throws IOException {
        int serverPort = 7777;
        Map<String, String> loginTable = new HashMap<>();

        ExecutorService executorService = Executors.newFixedThreadPool(100);
        DatagramSocket server = new DatagramSocket(serverPort);

        while (true) {
            System.out.println("就绪");
            byte[] container = new byte[1024];
            DatagramPacket datagramPacket = new DatagramPacket(container, container.length);
            server.receive(datagramPacket);
            Runnable runnable = () -> {
                try {
                    String[] receiveMsg = new String(datagramPacket.getData(), 0, datagramPacket.getLength()).split("-");

                    // 处理要给客户端发送的消息，需要拿到客户端的ip和port
                    String clientAddress = datagramPacket.getAddress().getHostAddress();
                    int clientPort = datagramPacket.getPort();
                    String msg;
                    String mode = receiveMsg[0];
                    String userName = receiveMsg[1];
                    String password = receiveMsg[2];
                    if (Integer.parseInt(mode) == 1) {
                        // 登录逻辑，判断账号密码
                        if (loginTable.getOrDefault(userName, "").equals(password)) {
                            msg = "密码正确";
                        } else {
                            msg = "用户名或密码有误";
                        }
                    } else {
                        // 注册逻辑
                        loginTable.put(userName, password);
                        msg = "注册成功";
                    }
                    System.out.println(msg);
                    byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);
                    DatagramPacket ServerAnswerPacket = new DatagramPacket(bytes, bytes.length, new InetSocketAddress(clientAddress, clientPort));
                    server.send(ServerAnswerPacket);
                    System.out.println("服务端发送成功 " + new String(ServerAnswerPacket.getData(), 0, ServerAnswerPacket.getLength()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            };
            executorService.submit(runnable);
        }
    }
}